package com.smart.dao;

import com.smart.domain.StudentUser;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/*数据库连接类  该类中包含一个插入学生信息到数据库的方法和一个获得本实例的静态方法*/
public class DBinsert {
    private static DBinsert instance = null;
    public static DBinsert getInstance() {
        if (instance == null) {
            instance = new DBinsert();
        }
        return instance;
    }
    public boolean stuinsert(StudentUser user) {
        final String DRIVER = "com.mysql.jdbc.Driver";
        final String USER = "root";
        final String PWD = "147852369";
        final String URL = "jdbc:mysql://localhost:3306/student";// 建立数据库连接
        Connection connection=null;
        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL,USER,PWD);
            String sql = "insert into stu(name,id,sex,sclass,grade) values(?,?,?,?,?)"; // insert语句
            PreparedStatement  pstmt = connection.prepareStatement(sql); // 创建用户操作执行SQL语句的PreparedStatement对象
            pstmt.setString(1, user.getName());
            pstmt.setString(2, user.getId());
            pstmt.setString(3, user.getSex());
            pstmt.setString(4, user.getSclass());
            pstmt.setString(5, user.getGrade());
            pstmt.executeUpdate(); // 编译执行insert语句
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;

    }

}